package com.maozai.maozaimall.product.web;

import com.maozai.maozaimall.product.entity.CategoryEntity;
import com.maozai.maozaimall.product.service.CategoryService;
import com.maozai.maozaimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @GetMapping({"/index.html", "/"})
    public String indexPage(Model model) {
        //TODO 1 查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }

    //index/catalog.json

    @GetMapping("index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //1 获取一把锁
        RLock mylock = redisson.getLock("my-lock");
        //2 加锁
        mylock.lock();
        //1 锁的自动续期，如果业务超长，运行期间自动给锁续上30s，不用担心业务时间长，锁自动过期
        //2 加锁的业务只要运行完成，就不会给当前续期，即使不手动解锁，锁默认在30s后自动删除
        try {
            System.out.println("加锁成功，执行业务");
            Thread.sleep(30000);
        }catch (Exception e) {

        }finally {
            //redisson在执行的时候，就算电脑宕机了也是不会发生死锁的
            System.out.println("释放锁");
            mylock.unlock();
        }
        return "hello";
    }
}
